package com.eazyshop.gateway.filter;

import com.eazyshop.gateway.utils.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * 网关认证过滤器
 */
@Component
public class AuthenticateFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 对于登录请求放行
        URI uri = request.getURI();
        // 如果请求的uri中包含/admin/login就是请求登录直接放行
        if(uri.toString().contains("/admin/login")){
            return  chain.filter(exchange);
        }
        // 如果不是登录请求要对令牌进行验证
        HttpHeaders headers = request.getHeaders();

        String token = headers.getFirst("token");
        // 如果请求头中没有token返回错误代码
        if(StringUtils.isEmpty(token)){
            // 设置响应头信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 返回设置的响应头信息

            return response.setComplete();
        }
        // 对令牌进行验证
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            // 验证失败
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            return response.setComplete();
        }
        // 验证通过
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 3;
    }
}
